package com.myblog.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.server.HttpServerResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.myblog.common.dto.LoginDto;
import com.myblog.common.lang.Result;
import com.myblog.entity.User;
import com.myblog.service.UserService;
import com.myblog.util.JwtUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

/**
 * 登录接口开发
 */
@RestController
public class AccountController {
    @Autowired
    JwtUtil jwtUtils;
    @Autowired
    UserService userService;
    /**
     * 默认账号密码 。
     * 登录的逻辑其实很简答，只需要接受账号密码，
     * 然后把用户的id生成jwt，返回给前段，为了后续的jwt的延期，
     * 所以我们把jwt放在header上。具体代码如下：
     */
    @CrossOrigin
    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginDto loginDto, HttpServletResponse response){
        System.out.println(loginDto.getUsername());
        User user = userService.getOne(new QueryWrapper<User>().eq("username",loginDto.getUsername()));
        Assert.notNull(user,"用户不存在");
        if(!user.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))){
            return Result.fail("密码错误");
        }
        // 生成jwt
       String jwt = jwtUtils.generateToken(user.getId());
        System.out.println(jwt);
        response.setHeader("Authorization",jwt);
        response.setHeader("Access-Control-Expose-Headers", "Authorization");
        // 用户可以另一个接口
        return Result.succ(MapUtil.builder()
                .put("id",user.getId())
                .put("username",user.getUsername())
                 .put("avatar",user.getAvatar())
                .put("email",user.getEmail())
        .map());
    }
    @GetMapping("/logout")
    @RequiresAuthentication
    public Result logout(){
        SecurityUtils.getSubject().logout();
        return  Result.succ(null);
    }
    // 退出

}
